package com.cby.code.encrypt;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * aes加密方式，保证与php服务端相同规则
 * 参考https://blog.csdn.net/flydream3618/article/details/86759420
 */
public class AESUtils {

  /**
   *  IV长度应该为16，请跟服务端保持一致
   */
  private static final String iv = "1234567812345678";

  /**
   * AES/CBC/PKCS5Padding默认对应PHP则为：AES-128-CBC
   * */
  private static final String CBC_PKCS5_PADDING = "AES/CBC/PKCS5Padding";

  /**
   * //AES 加密
   */
  private static final String AES = "AES";

  /**
   *
   * @param key 密钥，这个key长度应该为16位，另外不要用KeyGenerator进行强化，否则无法跨平台
   * @param cleartext 需要加密的明文
   * @return
   */
  public static String encrypt(String iv, String key, String cleartext) {
    try {
      Cipher cipher = Cipher.getInstance(CBC_PKCS5_PADDING);
      SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), AES);
      IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
      cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
      byte[] encrypted = cipher.doFinal(cleartext.getBytes());

      //base64编码一下
      return Base64Utils.encode(encrypted);

    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  /**
   *
   * @param key 密钥，这个key长度应该为16位，另外不要用KeyGenerator进行强化，否则无法跨平台
   * @param encrypted
   * @return
   */
  public static String decrypt(String iv, String key, String encrypted){
    try {

      byte[] encrypted1 = Base64Utils.decodeToByte(encrypted);
      Cipher cipher = Cipher.getInstance(CBC_PKCS5_PADDING);
      SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), AES);
      IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
      cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
      byte[] original = cipher.doFinal(encrypted1);

      //转换为字符串
      return new String(original);
    }
    catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
}